<?php

namespace App\Http\Controllers;

use App\Business\BLL\Wechat\WechatPayment;
use App\Models\Arenacontest;
use App\Models\ArenacontestUser;
use App\Models\WechatUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ArenacontestUserController extends Controller
{
    public function signupList()
    {
        $arenacontestId = request()->input('id');
        $list = ArenacontestUser::where('arenacontest_id', $arenacontestId)
            ->with('user:id,name,head_img,nickname')
            ->select('id', 'user_id')
            ->get();

        return response()->json(
            [
                'recode' => 1,
                'list' => $list,
            ]
        );

    }

    public function signup()
    {
        $arenacontestId = request()->input('arenacontest');
        $userId = request()->input('user_id');

        //查询比赛信息
        $arenacontestInfo = Arenacontest::find($arenacontestId);
        if ($arenacontestInfo == null || $arenacontestInfo->status != 20) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '未找到赛事',
                ]
            );
        }
        $now = date("Y-m-d H:i:s");
        if ($now > $arenacontestInfo->signup_datetime) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '报名已经截止',
                ]
            );

        }
        //查询用户
        $userInfo = WechatUser::find($userId);
        if ($userInfo == null) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '用户不存在',
                ]
            );
        }else{
            if ($arenacontestInfo->integral>0){
                if($userInfo->score<$arenacontestInfo->integral){
                    return response()->json(
                        [
                            'recode' => 0,
                            'msg' => '积分不足',
                        ]
                    );
                }
            }
        }

        //查看用户是否已经报名
        $signupUser = ArenacontestUser::where([['arenacontest_id', $arenacontestId], ['user_id', $userId], ['pay_status', 20]])->first();
        if ($signupUser) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '您已经报名',
                ]
            );
        }


        return response()->json(
            [
                'recode' => 1,
                'msg' => '报名成功',
            ]
        );

    }

    /**
     * 擂台赛报名提交
     * @return \Illuminate\Http\JsonResponse
     */
    public function signupSubmit(Request $request)
    {
        $arenacontestId = request()->input('arenacontest_id');
        $contact = request()->input('contact');
        $wxcode = request()->input('wxcode');
        $file = $request->file("file");
        $price = request()->input('price');
        $userId = request()->input('user_id');

        //查询比赛信息
        $arenacontestInfo = Arenacontest::find($arenacontestId);
        if ($arenacontestInfo == null && $arenacontestInfo->status == 20) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '未找到赛事',
                ]
            );
        }
        $now = date("Y-m-d H:i:s");
        if ($now > $arenacontestInfo->signup_datetime) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '报名已经截止',
                ]
            );

        }
        //查询用户
        $userInfo = WechatUser::find($userId);
        if ($userInfo == null) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '用户不存在',
                ]
            );
        }

        //查看用户是否已经报名
        $signupUser = ArenacontestUser::where([['arenacontest_id', $arenacontestId], ['user_id', $userId], ['pay_status', 20]])->first();
        if ($signupUser) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '您已经报名',
                ]
            );
        }
        $ArenacontestUser = new ArenacontestUser;
        if ($file) {
            // 将视频移动到指定的存储位置七牛
            $disk = \Storage::disk('qiniu');
            $filepath = $disk->put('arenacontes', $file);
//            $path = $file->store('videos', 'admin');//本地存储
            $ArenacontestUser->ball_video = $filepath;
        }

        //保存报名数据
        $ArenacontestUser->arenacontest_id = $arenacontestId;
        $ArenacontestUser->user_id = $userId;
        $ArenacontestUser->status = 10;
        $ArenacontestUser->contact = $contact;
        $ArenacontestUser->wxcode = $wxcode;
        if ($price>0){
            $ArenacontestUser->pay_status = 10;
        }else{
            $ArenacontestUser->pay_status = 20;
        }

        $ArenacontestUser->ordersn = getorderSN();
        $ArenacontestUser->price = $price;
        $ArenacontestUser->save();
        //更新报名人数
        $info = Arenacontest::find($arenacontestId);
        if ($info) {
            $info->numcount += 1;
            $info->save();
        }
        if ($price>0){
            //回调url
            $notifyUrl = route('wechat.pay.signupcallback');

            $app = WechatPayment::make();

            $jssdk = $app->jssdk;

            $result = $app->order->unify([
                'body' => '擂台赛报名',
                'out_trade_no' => $ArenacontestUser->ordersn,
                'trade_type' => 'JSAPI',
                'openid' => $userInfo->openid,
                'total_fee' => $ArenacontestUser->price*100,
                'notify_url' => $notifyUrl,
            ]);
            if ($result['return_code'] === 'SUCCESS') {
                $prepayId = $result['prepay_id'];
                $params = $jssdk->sdkConfig($prepayId);
                return response()->json(["recode" => 1, "params" => $params]);
            } else {
                return response()->json(["recode" => 0, "msg" => $result]);
            }
        }else{
            return response()->json(['recode' => 2, 'id' => $ArenacontestUser->id, 'msg' => '报名成功']);
        }
    }

    /**
     * 待付款调用支付
     * @return \Illuminate\Http\JsonResponse
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function pay()
    {
        $arenacontestId = request()->input('arenacontest');
        $userId = request()->input('user_id');

        //查询比赛信息
        $arenacontestInfo = Arenacontest::find($arenacontestId);
        if ($arenacontestInfo == null && $arenacontestInfo->status == 20) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '未找到赛事',
                ]
            );
        }
        $now = date("Y-m-d H:i:s");
        if ($now > $arenacontestInfo->signup_datetime) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '报名已经截止',
                ]
            );

        }
        //查询用户
        $userInfo = WechatUser::find($userId);
        if ($userInfo == null) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '用户不存在',
                ]
            );
        }

        //查看用户是否已经报名
        $signupUser = ArenacontestUser::where([['arenacontest_id', $arenacontestId], ['user_id', $userId]])->first();
        if ($signupUser->pay_status==20) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '您已经报名',
                ]
            );
        }

        if ($signupUser->price>0){
            //回调url
            $notifyUrl = route('wechat.pay.signupcallback');

            $app = WechatPayment::make();

            $jssdk = $app->jssdk;

            $result = $app->order->unify([
                'body' => '擂台赛报名',
                'out_trade_no' => $signupUser->ordersn,
                'trade_type' => 'JSAPI',
                'openid' => $userInfo->openid,
                'total_fee' => $signupUser->price*100,
                'notify_url' => $notifyUrl,
            ]);
            if ($result['return_code'] === 'SUCCESS') {
                $prepayId = $result['prepay_id'];
                $params = $jssdk->sdkConfig($prepayId);
                return response()->json(["recode" => 1, "params" => $params]);
            } else {
                return response()->json(["recode" => 0, "msg" => $result]);
            }
        }else{
            return response()->json(['recode' => 2, 'id' => $signupUser->id, 'msg' => '报名成功']);
        }
    }

    public function signupcallback()
    {
        $app = WechatPayment::make();

        $response = $app->handlePaidNotify(function ($message, $fail) {
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            // $recharge = Mission::find($message['out_trade_no']);
            $recharge = ArenacontestUser::where('ordersn', $message['out_trade_no'])->first();

            if (!$recharge || $recharge->pay_status == 20) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    if ($recharge->pay_status == 10) {
                        //更新报名状态
                        $recharge->pay_status = 20;
                        $recharge->transid = $message['transaction_id'];
                        $recharge->paytime = date("Y-m-d H:i:s");
                        $recharge->save(); // 保存订单
                    }
                    // 用户支付失败
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
        return $response;
    }
}
